<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        dataset: {
          source: [
              ['占比', '总数', '类型'],
              [22, 58212, 'MOD总线告警'],
              [40.1, 78254, '水位告警'],
              [12.4, 41032, '功率告警'],
              [11.1, 12755, '出光告警'],
              [20.7, 20145, '高反告警'],
              [55.1, 79146, '散光告警']
          ]
        },
        grid: {containLabel: true},
        xAxis: {name: '总数'},
        yAxis: {type: 'category'},
        visualMap: {
            left: 'left',
            min: 0,
            max: 100,
            text: ['占比'],
            // Map the score column to color
            dimension: 0,
            inRange: {
                color: ['#D7DA8B', '#E15457']
            }
        },
        series: [
            {
                type: 'bar',
                encode: {
                    x: '总数',
                    y: '类型'
                }
            }
        ]
      })
    }
  }
}
</script>
